<?php
namespace plugin\ky_shouyin\app\service;

use support\Db;

class RechargeService
{
    /**
     * 会员充值
     */
    public function recharge($memberId, $amount, $giveAmount, $paymentMethod, $storeId, $staffId, $operatorId, $remark = '')
    {
        try {
            Db::beginTransaction();
            
            // 生成订单号
            $orderNo = $this->generateOrderNo();
            
            // 添加充值记录
            Db::table('ky_member_recharge')->insert([
                'order_no' => $orderNo,
                'member_id' => $memberId,
                'amount' => $amount,
                'give_amount' => $giveAmount,
                'payment_method' => $paymentMethod,
                'store_id' => $storeId,
                'staff_id' => $staffId,
                'operator_id' => $operatorId,
                'remark' => $remark,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            // 更新会员余额
            Db::table('ky_member')
                ->where('id', $memberId)
                ->increment('balance', $amount + $giveAmount);
            
            // 赠送积分
            if ($amount > 0) {
                $pointsService = new PointsService();
                $points = $pointsService->calculateRechargePoints($amount);
                if ($points > 0) {
                    $pointsService->addPoints(
                        $memberId,
                        $points,
                        5, // 5表示充值赠送
                        null,
                        "充值{$amount}元赠送"
                    );
                }
            }
            
            Db::commit();
            return ['code' => 0, 'msg' => '充值成功'];
        } catch (\Exception $e) {
            Db::rollBack();
            return ['code' => 1, 'msg' => '充值失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 生成订单号
     */
    private function generateOrderNo()
    {
        // 生成格式：CZ + 年月日时分秒 + 4位随机数
        return 'CZ' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }
    
    /**
     * 获取充值记录
     */
    public function getRechargeLog($memberId, $page = 1, $limit = 15)
    {
        $query = Db::table('ky_member_recharge')
            ->where('member_id', $memberId);
            
        $total = $query->count();
        
        $data = $query->offset(($page - 1) * $limit)
                     ->limit($limit)
                     ->orderBy('id', 'desc')
                     ->get();
                     
        return [
            'total' => $total,
            'data' => $data
        ];
    }
} 